<template>
  <div class="file-list">
    <!-- 单文件访问模式 -->
    <template v-if="isShowSingleFile">
      <div v-if="fileList && fileList.length > 1" class="file-list-title" @click="switchDialog">
        <i v-if="iconShow" class="el-icon-paperclip" style="color: #999999;font-size:15px;" />文件共{{ fileList.length }}个
      </div>
      <template v-else-if="fileList && fileList.length === 1">
        <div v-for="(item, index) in fileList" :key="index" class="hover-show" style="display:flex;align-items:center;position:relative;">
          <el-tooltip v-if="item.url" placement="top" effect="dark">
            <div slot="content" style="max-width: 200px;">
              <div>
                <div>文件名：{{ item.name }}</div>
                <div>上传时间：{{ item.time | format('YYYY-MM-DD HH:mm:ss') }}</div>
                <img v-if="isImage(item)" :src="item.url" class="prev-img" alt="">
              </div>
            </div>
            <div v-if="isImage(item) && showImage && singleRowImg" :style="fileNameStyle" class="url-file" @click="downloadFile(item.url, item.name)">
              <img :class="{'table-img':tableSingle}" :src="item.url" alt="">
            </div>
            <div v-else :style="fileNameStyle" class="url-file" @click="downloadFile(item.url, item.name)">
              {{ item.name }}
            </div>
          </el-tooltip>
          <div :class="{ 'table-single': tableSingle }" class="single-download-file" @click.stop="handleDownload(item, true)">下载</div>
          <div v-if="showDelete" class="delete-file el-icon-error" @click="deleteFile(item, index)"/>
        </div>
      </template>
      <div v-else>--</div>
    </template>
    <!-- 多文件访问模式 -->
    <template v-else>
      <div v-if="fileList && fileList.length > 0" class="file-list-title" @click="switchDialog">
        <i v-if="iconShow" class="el-icon-paperclip" style="color: #999999;font-size:15px;" />
        <slot name="fileTitle">文件共{{ fileList.length }}个</slot>
      </div>
      <div v-else>--</div>
    </template>

    <el-dialog
      v-if="fileList && fileList.length > 0"
      :visible.sync="dialogVisible"
      :before-close="switchDialog"
      :show-close="true"
      :append-to-body="true"
      :class="{'fitMobile':showMobilePage, 'edit-common-dialog-size': showPick || showDelete}"
      class="file-dialog small-common-dialog-size"
    >
      <u-table
        ref="orderTable"
        :height="400"
        :row-height="49"
        :data="fileList"
        :border="false"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row>
        <u-table-column
          align="left"
          label="序号"
          width="40">
          <template slot-scope="scope">
            <div>{{ scope.$index + 1 }}</div>
          </template>
        </u-table-column>
        <u-table-column
          align="left"
          label="文件名">
          <template slot-scope="scope">
            <div v-if="scope.row.url" class="url-file-container" >
              <el-tooltip placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">
                  <div>
                    <div>文件名：{{ scope.row.name }}</div>
                    <img v-if="isImage( scope.row)" :src="scope.row.url" class="prev-img" alt="">
                  </div>
                </div>
                <div class="url-file" @click="downloadFile(scope.row.url, scope.row.name)">
                  {{ scope.row.name }}
                </div>
              </el-tooltip>
            </div>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="上传时间" width="140px">
          <template slot-scope="scope">
            <div>{{ scope.row.time | format('YYYY/MM/DD HH:mm') }}</div>
          </template>
        </u-table-column>
        <u-table-column :width="operateCellWidth" align="left" label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleDownload(scope.row, true)"><div style="font-size:14px;">下载</div></el-button>
            <el-button v-if="showPick" :loading="scope.row.pickLoading" type="text" size="small" @click="pickFile(scope.row, scope.$index)">采集</el-button>
            <el-button v-if="showDelete" :loading="scope.row.delLoading" type="text" style="color: red" size="small" @click="deleteFile(scope.row, scope.$index)">删除</el-button>
          </template>
        </u-table-column>
      </u-table>
    </el-dialog>
  </div>
</template>

<script>
import { downloadFile, openNewWindow } from '@/utils';
import { format } from '@/filters/date';
import { mapState } from 'vuex';
export default {
  filters: { format },
  props: {
    fileList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    fileNameStyle: {
      type: Object,
      default: () => ({})
    },
    iconShow: {
      type: Boolean,
      default: false
    },
    showDelete: {
      type: Boolean,
      default: false
    },
    showImage: {
      type: Boolean,
      default: true
    },
    isShowSingleFile: {
      type: Boolean,
      default: false
    },
    tableSingle: {
      type: Boolean,
      default: false
    },
    singleRowImg: {
      type: Boolean,
      default: true
    },
    showPick: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    operateCellWidth() {
      let actionBtnNum = 0;
      if (this.showPick) actionBtnNum++;
      if (this.showDelete) actionBtnNum++;
      return ['50px', '90px', '130px'][actionBtnNum];
    }
  },
  methods: {
    downloadFile(url, name, download = false) {
      if (download) {
        downloadFile(url, name);
        return;
      }
      if (this.isImage({ name, url })) {
        window.open(url);
      } else if (this.isExcel(name)) {
        this.viewExcel(url, name);
      } else {
        downloadFile(url, name);
      }
    },
    viewExcel(url, name) {
      try {
        const timestamp = (new Date()).valueOf();
        const random = Math.ceil(Math.random() * 10);
        const lists = name.split('.');
        const fileName = `${timestamp}${random}.` + lists[lists.length - 1];
        const previewUrl = `${url}#&fullfilename=${fileName}`;
        const officeUrl = 'http://fileview.feibo.com/onlinePreview?url=' + encodeURIComponent(btoa(previewUrl));
        // window.open(officeUrl, '_blank');
        openNewWindow(officeUrl);
      } catch (error) {
        downloadFile(url, name);
      }
    },
    isExcel(name) {
      const excel = /(\.(doc|docx|xls|xlsx|xlsm|ppt|pptx|txt))$/i;
      return excel.test(name);
    },
    isPdf(srcName) {
      const img = /(\.(pdf))$/i;
      return img.test(srcName);
    },
    isImage(data) {
      const img = /(\.(gif|png|jpg|jpeg|webp|bmp|tif))$/i;
      // 名称不一定带img标识，图片路径也可能带
      return img.test(data.name) || img.test(data.url);
    },
    openImg(src) {
      window.open(src);
    },
    switchDialog() {
      this.dialogVisible = !this.dialogVisible;
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    pickFile(item, index) {
      this.$emit('pickFile', { file: item, index });
    },
    deleteFile(item, index) {
      this.$emit('removeFileList', { file: item, index });
    },
    handleDownload(row, download = false) {
      const { url, name, uid } = row;
      this.downloadFile(url, name, download);
      const params = {
        uid,
        name
      };
      this.$emit('download', params);
    }
  }
};
</script>

<style lang="scss" scoped>
.url-file-container {
  display: flex;
  align-items: center;
}
.delete-file {
  position: absolute;
  right: -5px;
  top: -5px;
  cursor: pointer;
  background: #fff;
  color: red;
  font-size: 15px;
  display: none;
}
.table-img{
  max-width: 120px;
  width: 120px;
  height: 25px;
}
.fitMobile {
  ::v-deep .el-dialog{
    width: 100% !important;
  }
}
.hover-show {
  position: relative;
  &:hover {
    .delete-file {
      display: block;
    }
  }
  .single-download-file {
    color: #406eff;
    cursor: pointer;
    margin-left: 10px;
    min-width: calc(4em + 10px);
  }
  .table-single{
    min-width: 28px;
  }
}
.url-file {
  color: #406eff;
  cursor: pointer;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  display: inline-block;
  &:hover {
    color: #406eff;
  }
  img {
    max-width: 100px;
    max-height: 100px;
  }
}
.prev-img {
  max-width: 100px;
  max-height: 100px;
  margin-top: 5px;
  object-fit: cover;
}
.file-list {
  display: inline-block;
  max-width: 100%;
  .file-list-title {
    color: #406eff;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    &:hover {
      color: #0f34aa;
    }
  }
}
.file-dialog {
  &::v-deep {
    .el-dialog {
      // border-radius: 12px;
      max-height: 530px;
    }
    .el-dialog__body {
      overflow: auto;
      .cell {
        padding: 0 5px;
      }
    }
  }
}
</style>
